/**
 * Copyright(c) Hainan eKing Technology co., LTD
 *
 * @date 2013年9月4日
 * 	
 * Original Author: 郑兴(zhengxing)
 *
 * ChangeLog
 *
 */
package com.hnas.sys.core.spring;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hnas.sys.core.util.CacheUtil;
import com.hnas.sys.dao.ResourceDAO;
import com.hnas.sys.orm.AuthorityResource;
import com.hnas.sys.orm.Resource;
import com.hnas.sys.service.system.AuthorityService;
import com.hnas.sys.service.system.mapper.ResourceMapper;

/**
 * @author 郑兴(zhengxing)
 *
 */
@Service("metaData")
public class MetaData {
	private LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
	
	@javax.annotation.Resource
	private ResourceDAO resourceDAO;
	@javax.annotation.Resource
	private AuthorityService authorityService;
	
	@PostConstruct
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public void loadSecurityInfos(){
		List<Resource> resources = resourceDAO.loadAllReference();
		CacheUtil.setResourceCache(ResourceMapper.getInstance().mapToValues(resourceDAO.loadAll()));
		CacheUtil.setAuthorityCache(authorityService.loadAll());
		for(Resource resource : resources) {
			RequestMatcher key = new AntPathRequestMatcher(resource.getResource()+"**");
			Collection<ConfigAttribute> configAttributes = new LinkedList<ConfigAttribute>();
			for(final AuthorityResource ar : resource.getAuthorityResources()) {
				configAttributes.add(new SecurityConfig("ROLE_" + ar.getAuthority().getId()));
			}
			this.requestMap.put(key, configAttributes);
		}
		CacheUtil.setMetaDataCache(resources);
	}

	/**
	 * @return the requestMap
	 */
	public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestMap() {
		return requestMap;
	}

	/**
	 * @param requestMap the requestMap to set
	 */
	public void setRequestMap(
			LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap) {
		this.requestMap = requestMap;
	}

	/**
	 * @return the resourceDAO
	 */
	public ResourceDAO getResourceDAO() {
		return resourceDAO;
	}

	/**
	 * @param resourceDAO the resourceDAO to set
	 */
	public void setResourceDAO(ResourceDAO resourceDAO) {
		this.resourceDAO = resourceDAO;
	}
	
}
